﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using System.Timers;
using Common;

namespace CPI311
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class WallGame : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;        // Drawing 2D stuff
        SpriteFont textFont;            // Object for a font
        Texture2D world;          // Object for a texture
        BasicEffect effect;
        Common.Plane plane;
        Common.HeightMap heightMap;
        Common.BitmapWorld bitmapWorld;
        Timer timer;

        bool useHeightMap = false;

        KeyboardState prevKeyboardState = Keyboard.GetState();

        Camera camera;
        ModelObject player;


        public WallGame()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

            timer = new Timer();
            timer.Interval = 1000;
            timer.AutoReset = true;
            timer.Elapsed += OnTimerDone;
            timer.Start();
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();

        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here
            camera = new Camera();
            camera.Position = new Vector3(0, 0, -20);
            camera.AspectRatio = GraphicsDevice.Viewport.AspectRatio;

            plane = new Common.Plane(99);
            plane.Texture = Content.Load<Texture2D>("Textures/Jellyfish");
            plane.Scale *= 50;

            player = new ModelObject();
            player.Model = Content.Load<Model>("Models/Sphere");

            world = Content.Load<Texture2D>("Textures/World");

            heightMap = new HeightMap(world);
            heightMap.Scale *= 50;
            bitmapWorld = new BitmapWorld(world);

            effect = new BasicEffect(GraphicsDevice);
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();
            // TODO: Add your update logic here
            KeyboardState keyboardState = Keyboard.GetState();


            if (keyboardState.IsKeyDown(Keys.W))
            {
                Vector3 newPosition = player.Position + Vector3.Transform(Vector3.UnitZ, player.Rotation)*gameTime.ElapsedGameTime.Milliseconds/1000f;
                if (bitmapWorld.GetElevationBilinear(new Vector2((50 + newPosition.X) / 100, (50 + newPosition.Z) / 100)) < 0.05f)
                {
                    player.Position = newPosition;
                }
            }
            if (keyboardState.IsKeyDown(Keys.A))
            {
                player.RotateY = gameTime.ElapsedGameTime.Milliseconds / 100f;
            }
            if (keyboardState.IsKeyDown(Keys.S))
            {
                player.RotateY = -gameTime.ElapsedGameTime.Milliseconds/100f;
            }
            float f = bitmapWorld.GetElevationBilinear(new Vector2((50 + player.Position.X) / 100, (50 + player.Position.Z) / 100));
            camera.Position = player.Position - Vector3.Transform(Vector3.UnitZ, player.Rotation)*5 + Vector3.UnitY*2;

            if (keyboardState.IsKeyDown(Keys.Tab) && prevKeyboardState.IsKeyUp(Keys.Tab))
                useHeightMap = !useHeightMap;

            prevKeyboardState = keyboardState;
            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            // Clear the screen
            GraphicsDevice.Clear(Color.Goldenrod);
            // Set the Depth Stencil State to default for 3D rendering
            GraphicsDevice.DepthStencilState = new DepthStencilState();
            // Setup some colors for lighting
            effect.EmissiveColor = new Vector3(0.2f, 0.2f, 0.2f);
            effect.DiffuseColor = new Vector3(0.5f, 0.0f, 0.0f);
            effect.SpecularColor = new Vector3(0.0f, 0.5f, 0.0f);
            effect.SpecularPower = 10;
            effect.LightingEnabled = true; // Enable lighting!
            // Some parameters for the Directional lighting
            effect.DirectionalLight0.Direction = new Vector3(0, -1, 1);
            effect.DirectionalLight0.SpecularColor = Vector3.One;
            // Provide the different matrices
            effect.View = camera.View;
            effect.Projection = camera.Projection;

            effect.TextureEnabled = true;
            effect.Texture = plane.Texture;
            if (useHeightMap)
            {
                effect.World = heightMap.World;
                heightMap.Draw(effect);
            }
            else
            {
                effect.World = plane.World;
                plane.Draw(effect);
            }

            effect.TextureEnabled = false;
            player.Draw(camera.View, camera.Projection);


            // TODO: Add your drawing code here

            base.Draw(gameTime);
        }

        private void OnTimerDone(object sender, ElapsedEventArgs args)
        {
            useHeightMap = !useHeightMap;
        }
    }
}
